<!--产品信息-->
<template>
  <div class="product-define">
    <div v-loading="loading" class="form-wrap">
      <el-form ref="form" class="define-form" :model="form" :rules="rules" label-width="123px" label-position="left">
        <el-row>
          <el-col>
            <el-form-item label="产品ID（PID）" class="form-item" :class="{ 'no-edit-item': editStatus }">
              {{ form.productId }}
            </el-form-item>
            <el-form-item label="产品类型" class="form-item" :class="{ 'no-edit-item': editStatus }">
              {{ form.categoryName || '-' }}
            </el-form-item>
            <el-form-item label="客户名称" :prop="editStatus ? 'customerCode' : ''" :class="{ 'form-item': !editStatus }">
              <el-select v-show="editStatus" v-model="form.customerCode" placeholder="请选择客户名称" @change="handleCustomer">
                <el-option
                  v-for="item in customerData"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"></el-option>
              </el-select>
              <span v-show="!editStatus">{{ form.customerName || '-' }}</span>
            </el-form-item>
            <el-form-item label="产品名称" :prop="editStatus ? 'name' : ''" :class="{ 'form-item': !editStatus }">
              <el-input
                v-show="editStatus"
                v-model="form.name"
                placeholder="请输入产品名称"
                maxlength="64"
                show-word-limit
                clearable></el-input>
              <span v-show="!editStatus">{{ form.name || '-' }}</span>
            </el-form-item>
            <el-form-item label="产品型号" :prop="editStatus ? 'productModel' : ''" :class="{ 'form-item': !editStatus }">
              <el-input
                v-show="editStatus"
                v-model="form.productModel"
                placeholder="请输入产品型号"
                maxlength="64"
                show-word-limit
                clearable></el-input>
              <span v-show="!editStatus">{{ form.productModel || '-' }}</span>
            </el-form-item>
            <el-form-item label="设备类型">
              <span>{{ deviceType || '-' }}</span>
            </el-form-item>
            <el-form-item
              label="通讯协议"
              :prop="editStatus ? 'communicationProtocol' : ''"
              :class="[!editStatus ? 'form-item' : 'edit-form-item']">
              <ul v-show="editStatus">
                <li
                  v-for="(item, index) in communicationProtocolData"
                  :key="index"
                  :class="{ 'selected': item === form.communicationProtocol }"
                  @click="selectCommunicationProtocol(index, item)">
                  {{
                    item }}</li>
              </ul>
              <span v-show="!editStatus">{{ form.communicationProtocol || '-' }}</span>
            </el-form-item>
            <el-form-item
              v-if="editStatus"
              label="配网方式"
              prop="networkDistributeMode"
              class="edit-form-item">
              <ul>
                <li
                  v-for="(item, index) in dmsMethods"
                  :key="index"
                  :class="{ 'selected': item === form.networkDistributeMode }"
                  @click="selectedDmsMethods(index, item)">{{
                    item }}</li>
              </ul>
            </el-form-item>
            <el-form-item
              v-if="!editStatus"
              label="配网方式"
              class="form-item">
              {{ form.networkDistributeMode || '-' }}
            </el-form-item>
            <el-form-item label="产品图片" class="form-item-img" :class="{ 'no-edit-item': editStatus }">
              <div v-show="editStatus" class="product-img">
                <el-upload
                  class="upload-img"
                  action="/admin/sys-file/upload"
                  :headers="headers"
                  :show-file-list="false"
                  :on-success="handleSuccess"
                  :on-error="uploadError"
                  :before-upload="beforeUpload">
                  <img v-if="form.icon" :src="uploadUrl || form.icon" class="uploaded-img">
                  <div v-else>
                    <i class="iconfont icon-shangchuantupian"></i>
                    <div class="text">点击上传</div>
                  </div>
                </el-upload>
                <!-- <div class="img-rule">
                  <p>尺寸：480*480px</p>
                  <p>格式：png</p>
                  <p>大小：100kb以内</p>
                </div> -->
              </div>
              <div v-show="!editStatus">
                <img v-if="form.icon" :src="`${form.icon}?t=${new Date().getTime()}`" alt="">
                <span v-else>-</span>
              </div>
            </el-form-item>
            <el-form-item label="产品说明" :prop="editStatus ? 'description' : ''" :class="{ 'form-item': !editStatus }">
              <el-input
                v-show="editStatus"
                v-model="form.description"
                type="textarea"
                maxlength="200"
                show-word-limit
                placeholder="请输入产品说明，尽可能描述清楚"
                :rows="4"></el-input>
              <span v-show="!editStatus">{{ form.description }}</span>
            </el-form-item>
            <el-form-item label="创建时间" :class="{ 'no-edit-item': editStatus }">
              {{ form.updateTime }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="btn">
      <el-tooltip v-if="developStatus == 1" content="产品已发布，信息不可修改，如需修改，请返回开发状态" placement="top">
        <div class="disbled">
          <el-button
            v-show="!editStatus"
            type="primary"
            size="14"
            :disabled="rolesCode === 'SALE' || developStatus == 1"
            @click="onEdit">编辑</el-button>
        </div>
      </el-tooltip>
      <div v-else>
        <el-button
          v-show="!editStatus"
          type="primary"
          size="14"
          :disabled="rolesCode === 'SALE'"
          @click="onEdit">编辑</el-button>
      </div>
      <el-button v-show="editStatus" class="cancel" size="14" @click="onCancel">取消</el-button>
      <el-button v-show="editStatus" type="primary" size="14" :disabled="saveBtnDisabled" @click="onSubmit">保存</el-button>
    </div>
  </div>
</template>
<script>
import { queryProduct, updateProduct } from '@/api/product/product-details'
import { customer, scheme } from '@/api/product/create-product'
import { mapGetters } from 'vuex'
import store from '@/store'
export default {
  name: 'productDefine',
  data() {
    return {
      formInfo: { // 产品信息
        wiredNetwork: 0 // 有线联网
      },
      radioValue: 1,
      virtualRadioValue: 1,
      isDisabled: true,
      headers: {
        'TENANT-ID': store.getters.userInfo.tenantId,
        Authorization: 'Bearer ' + store.getters.access_token
      },
      form: {
        productId: '', // 产品ID
        categoryCode: '', // 产品类型
        customerCode: '', // 客户名称
        productModel: '', // 产品型号
        name: '', // 产品名称
        communicationProtocol: '', // 通讯协议
        networkDistributeMode: '', // 配网方式
        icon: '', // 产品icon
        description: '', // 产品说明
        updateTime: '' // 创建时间
      },
      deviceType: '', // 设备类型
      communicationProtocolData: '', // 通讯协议
      dmsMethods: '', // 配网方式
      selectedNetwork: '', // 选中联网方式索引
      selectedDms: '', // 选中配网方式索引
      dialogVisible: false,
      editStatus: false, // 编辑状态
      productId: '', // 产品id
      productInfoData: {}, // 产品信息
      customerData: [], // 客户信息
      deviceTypeMap: {
        'device': '普通设备',
        'childrenDevice': '网关子设备',
        'gateway': '网关设备'
      },
      rules: {
        customerCode: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        productModel: [
          { required: true, message: '请输入产品型号', trigger: 'blur' }
        ],
        communicationProtocol: [
          { required: true, message: '请选择通讯协议', trigger: 'click' }
        ],
        networkDistributeMode: [
          { required: true, message: '请选择配网方式', trigger: 'click' }
        ],
        icon: [
          { required: true, message: '请上传产品图片', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入产品说明', trigger: 'blur' }
        ]
      },
      submitFlag: true,
      uploadUrl: '',
      loading: true
    }
  },
  computed: {
    ...mapGetters(['rolesCode']),
    // 保存按钮置灰
    saveBtnDisabled() {
      // 遍历 form 对象的所有属性
      for (const key in this.form) {
        if (Object.prototype.hasOwnProperty.call(this.form, key)) {
          // 如果属性值为空字符串，则返回 true 禁用按钮
          if (this.form[key] === '') {
            return true
          }
        }
      }
      // 如果所有属性都不为空，则返回 false 启用按钮
      return false
    }
  },
  created() {
    this.productId = this.$route.query.productId
    this.developStatus = this.$route.query.developStatus
    this.queryDefineList()
    this.queryCustomer()
    this.queryScheme()
  },
  methods: {
    // 产品信息数据
    queryDefineList() {
      this.loading = true
      const params = {
        productId: this.productId
      }
      queryProduct(params).then(res => {
        const { data } = res.data
        this.productInfoData = data
        this.form = {
          productId: data.productId,
          categoryCode: data.categoryCode,
          categoryName: data.categoryName,
          name: data.name,
          customerCode: data.customerCode,
          customerName: data.customerName,
          productModel: data.productModel,
          communicationProtocol: data.communicationProtocol,
          networkDistributeMode: data.networkDistributeMode,
          icon: data.icon,
          description: data.description,
          updateTime: data.updateTime
        }
        this.deviceType = data.deviceType
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    // 获取客户信息
    queryCustomer() {
      customer().then(res => {
        this.customerData = res.data.data.records
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 选择客户名称
    handleCustomer(code) {
      this.form.customerName = this.customerData.find(item => item.code === code).name
    },
    // 获取联网方式和配网方式
    queryScheme() {
      scheme().then(res => {
        this.communicationProtocolData = res.data.data.communicationProtocol
        this.dmsMethods = res.data.data.networkDisMode || res.data.data.networkDistributeMode
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 选择通讯协议
    selectCommunicationProtocol(index, item) {
      this.form.communicationProtocol = item
    },
    // 选择配网方式
    selectedDmsMethods(index, item) {
      this.form.networkDistributeMode = item
    },
    // 编辑
    onEdit() {
      this.editStatus = true
      this.selectedDms = this.form.networkDistributeMode
    },
    /**
     * 修改产品信息
     * @param productId 产品ID
     * @param categoryCode 产品类型
     * @param customerCode 客户名称
     * @param productModel 产品型号
     * @param name 产品名称
     * @param networkDistributeMode 配网方式
     * @param icon 产品icon
     * @param description 产品说明
     */
    onSubmit() {
      const params = {
        ...this.form
      }
      updateProduct(params).then(res => {
        this.queryDefineList()
      }).catch(err => {
        this.$message.error(err.message)
      })
      this.editStatus = false
    },
    // 取消
    onCancel() {
      this.queryDefineList()
      this.editStatus = false
    },
    // 产品图片上传成功
    handleSuccess(res, file) {
      this.form.icon = res.data.url
      this.uploadUrl = URL.createObjectURL(file.raw)
    },
    // 上传失败
    uploadError(err, file, fileList) {
      this.$message.error(err)
    },
    // 产品图片上传之前
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        // 校验图片格式是否为png
        const isPng = file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg'
        if (!isPng) {
          this.$message.error('只能上传png/jpg/jpeg格式的图片')
          return
        }
        // 使用FileReader获取图片尺寸
        const reader = new FileReader()
        reader.onload = (e) => {
          const image = new Image()
          image.onload = () => {
            // 校验图片尺寸是否为480x480
            // const width = image.width
            // const height = image.height
            // if (width === 480 && height === 480) {
            //   // 校验图片大小是否小于100M
            //   if (file.size <= 100 * 1024 * 1024) {
            //     resolve(file)
            //   } else {
            //     this.$message.error('图片大小不能超过100M')
            //   }
            // } else {
            //   this.$message.error('图片尺寸必须为480x480')
            // }
            // 校验图片大小是否小于100M
            if (file.size <= 100 * 1024 * 1024) {
              resolve(file)
            } else {
              this.$message.error('图片大小不能超过100M')
            }
          }
          image.src = e.target.result
        }
        reader.readAsDataURL(file)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.product-define {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  height: 100%;

  .form-wrap {
    flex-grow: 1;

    .define-form {
      margin-left: 60px;

      .el-select,
      .el-input,
      .el-textarea {
        width: 468px;
      }

      .no-edit-item ::v-deep .el-form-item__label {
        margin-left: 10px !important;
        width: 113px !important;
      }

      ul {
        list-style: none;
        display: flex;
        padding: 0;
        margin: 0;

        li {
          padding: 0 18px;
          border-radius: 6px;
          border: 1px solid #DEDEDE;
          margin-right: 14px;
          cursor: pointer;
        }

        li:hover {
          border: 1px solid #275FE8;
        }

        .selected {
          background: #275FE8;
          color: #fff;
        }
      }

      .product-img {
        display: flex;

        .upload-img {
          .uploaded-img {
            width: 80px;
            height: 80px;
          }

          ::v-deep .el-upload {
            width: 80px;
            height: 80px;
            border: 1px dashed #DEDEDE;
            border-radius: 4px;
            font-weight: 400;
            color: #808080;
          }

          .icon-shangchuantupian {
            width: 32px;
            height: 32px;
            font-size: 32px;
            position: absolute;
            top: 11px;
            left: 25px;
          }

          .text {
            margin-top: 40px;
          }
        }

        .img-rule {
          font-size: 12px;
          font-weight: 400;
          color: #808080;
          margin-left: 15px;

          p {
            height: 14px;
            line-height: 14px;
          }
        }
      }
    }
  }

  .el-form-item--small.el-form-item {
    margin-bottom: 16px;
  }

  .form-item {
    line-height: 20px;
  }

  .edit-form-item ::v-deep .el-form-item__label,
  .edit-form-item ::v-deep .el-form-item__content {
    line-height: 32px !important;
  }

  .form-item-img {
    img {
      width: 80px;
      height: 80px;
    }
  }

  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
  }

  .btn {
    width: 100%;
    text-align: center;
    margin: 20px 0;

    .cancel {
      margin-right: 16px;
    }
  }
}

::v-deep .el-textarea .el-input__count {
  background: transparent;
  right: 20px;
  bottom: 0px;
}

::v-deep .el-form-item--small .el-form-item__content,
::v-deep .el-form-item--small .el-form-item__label {
  line-height: 20px;
}
</style>
<style>
.el-button--disabled-hover.is-disabled:hover {
  background-color: #c0c0c0 !important;
  cursor: not-allowed;
}
</style>

